import Router from 'vue-router';
import router, { asyncRouterMap } from '../router';
import { compare, Flatten } from '../utils/common';
//退出登录
export const logout = ({ commit }) => {
  return new Promise((resolve) => {
    commit('LOGOUT');
    resolve();
  });
};
//清除缓存
export const clear = ({ commit }) => {
  return new Promise((resolve) => {
    commit('CLEAR');
    resolve();
  });
};
//添加页签路由
export const addVisitedViews = ({ commit }, view) => {
  return commit('ADD_VISITED_VIEWS', view);//去触发ADD_VISITED_VIEWS，并传入参数
};
//关闭页签--删除路由数据的方法
export const delVisitedViews = ({ commit, state }, view) => {
  return new Promise((resolve) => {
    const list = JSON.parse(JSON.stringify(state.visitedviews));//上一次的页签集合
    commit('DEL_VISITED_VIEWS', view);
    resolve({ visitedviews: [...state.visitedviews], view: list });//resolve方法：成功后回调的方法,返回新的state.visitedviews
  })
};
//匹配过滤路由
export const filterRouter = ({ commit, state }, list) => {
  return new Promise((resolve) => {
    const parent = "/Index";
    const data = JSON.parse(JSON.stringify(list));
    const routes = Flatten(data, "child", true);
    const options = [];
    asyncRouterMap.forEach(item => {
    
      routes.forEach(self => {
        if (item.path === self.url) {
          const obj = {
            path: item.path,
            name: item.name,
            component: item.component,
            meta: {
              keepAlive: item.meta.keepAlive,
              closable: item.meta.closable,
              bar: item.meta.bar,
              list: item.meta.list,
              title: self.name,
            },
          };
          options.push(obj);
        }
      });
    });
 
    const index = router.options.routes.map(v => v.path).indexOf(parent);
    if (index > -1) {
      router.matcher = new Router().matcher;
      router.options.routes[index].children = options;
      console.log(router)
      router.addRoutes(router.options.routes.concat([{//捕获未定义的路由配置
        path: '*',
        redirect: '/NotFound',
        hidden: true,
      }]));

      const home = !options || options === null || options.length === 0 ? {} : options[0];
      commit('FILTER_ROUTER', { list: home, type: 'home' });
      resolve(home);
    }
  });
};
//匹配过滤导航菜单
export const filterMenus = ({ commit, state }, list) => {
  return new Promise((resolve) => {
    const routes = Flatten(JSON.parse(JSON.stringify(list)), "child", true);
    const data = Flatten(JSON.parse(JSON.stringify(state.menus)), "children", true);
    const path = data.map(v => v.path);
    const arr = [];
    routes.forEach(item => {
      const index = path.indexOf(item.url);
      if (index > -1) {
        const self = data[index];
        const obj = {
          icon: self.icon ? self.icon : "",
          name: self.name,
          path: self.path,
          sortId: item.sortId,
          title: item.name,
          id: item.id,
          parentId: item.parentId,
        };
        arr.push(obj);
      }
    });
    const parent = arr.filter(v => v.parentId === 0).sort(compare('sortId'));
    const menus = recombineMenus(arr, parent);
    commit('FILTER_ROUTER', { list: menus, type: 'role' });
    resolve();
  });
};
//数组重组获取导航菜单
const recombineMenus = (data, list) => {
  list.forEach(item => {
    item.children = [];
    for (let j = 0; j < data.length; j++) {
      if (data[j].parentId === item.id) {
        item.children.push(data[j]);
      }
      else {
        if (item.children) {
          recombineMenus(data, item.children)
        }
      }
    }
  
    if (item.children.length === 0) {
      delete item.children;
    }
  });
  return list.sort(compare('sortId'));
};
